package com.cwh.springbootMybatis.controller;

import com.cwh.springbootMybatis.entity.SssfmIoBill;
import com.cwh.springbootMybatis.entity.SssfmIoBillItem;
import com.cwh.springbootMybatis.entity.SssfmIoBillItem01;
import com.cwh.springbootMybatis.entity.User;
import com.cwh.springbootMybatis.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.*;

/**
 * @ClassName ImportData
 * @Description ImportData
 * @Author gxx
 * @Date 2020/3/27 16:09
 * @Version 1.0
 */
@RestController
@RequestMapping("/data")
public class ImportData {
    @Autowired
    private SssfmIoBillItem01Mapper sssfmIoBillItem01Mapper;
    @Autowired
    private SssfmIoBillItemMapper sssfmIoBillItemMapper;
    @Autowired
    private SssfmIoBillMapper sssfmIoBillMapper;
    @Autowired
    SssfmIoBillQtcyMapper sssfmIoBillQtcyMapper;
    @Autowired
    SssfmIoBillItemQtcyMapper sssfmIoBillItemQtcyMapper;
    @Autowired
    SssfmIoBillItem01QtcyMapper sssfmIoBillItem01QtcyMapper;

    @RequestMapping("/import")
    public String importdata(HttpServletRequest request) throws Exception {
        String s = request.getParameter("flag");
        if ("1".equals(s)) {
            sssfmIoBillMapper.createTable("sssfm_io_bill");
            sssfmIoBillMapper.createTable("sssfm_io_bill" + "_bak");
            sssfmIoBillMapper.createTableqtcy("sssfm_io_bill" + "_qtcy");
            sssfmIoBillItemMapper.createTable("sssfm_io_bill_item");
            sssfmIoBillItemMapper.createTable("sssfm_io_bill_item" + "_bak");
            sssfmIoBillItemMapper.createTableqtcy("sssfm_io_bill_item" + "_qtcy");
            sssfmIoBillItem01Mapper.createTable("sssfm_io_bill_item01");
            sssfmIoBillItem01Mapper.createTable("sssfm_io_bill_item01" + "_bak");
            sssfmIoBillItem01Mapper.createTableqtcy("sssfm_io_bill_item01" + "_qtcy");
        }
        System.out.println(request.getParameter("path"));
        File dir = new File(request.getParameter("path"));
//        File dir=new File("/Users/zhengchenggong/Desktop/tmp/数据库恢复/宁夏数据库/biao");
        listFile(dir, "");
        return "";
    }

    @RequestMapping("/bak")
    public String bak(HttpServletRequest request) throws Exception {

        String size = request.getParameter("size");
        int sizeInt = Integer.valueOf(size);
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=1;i<=sizeInt;i++){
                    insertTable(i);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=1;i<=sizeInt;i++){
                    insertItemTable(i);
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i=1;i<=sizeInt;i++){
                    insertItem01Table(i);
                }
            }
        }).start();

        return null;
    }


    //主表
    private void insertTable(int i){
        //计算目标需要   新增的数据
        List list = sssfmIoBillMapper.queryStep1("sssfm_io_bill_"+i);
        //判断 临时表 是否可以 接收目标表的数据  查询结果没有不需要 第三步
        List mb = sssfmIoBillMapper.queryStep2("sssfm_io_bill_"+i);
        if (mb != null && !mb.isEmpty()) {//需要处理
            List<SssfmIoBill> nowdata = sssfmIoBillMapper.selectByIds("sssfm_io_bill_"+i, mb);
            List<SssfmIoBill> bakdata = sssfmIoBillMapper.selectByIdsbak(mb);
            Map tmp1 = new HashMap<>();
            Map tmp2 = new HashMap<>();
            for (SssfmIoBill sb : nowdata) {
                tmp1.put(sb.getBillId(), sb);
            }
            for (SssfmIoBill sb : bakdata) {
                tmp2.put(sb.getBillId(), sb);
            }
            Iterator iterator = tmp1.entrySet().iterator();
            List<SssfmIoBill> daicha = new ArrayList();//bak待插入
            List<String> delIds = new ArrayList<>();//bak待删除
            List<SssfmIoBill> qtcy = new ArrayList();//求同存异表
            List<String> delSameIds = new ArrayList<>();//bak和待插数据一模一样时记录下来，并删除

            while (iterator.hasNext()) {
                Map.Entry<String, SssfmIoBill> entry = (Map.Entry<String, SssfmIoBill>) iterator.next();
                String bill_id = (String) entry.getKey();
                SssfmIoBill sBillbak = entry.getValue();
                SssfmIoBill sBill = (SssfmIoBill) tmp2.get(bill_id);
                System.out.println(sBill.equals(sBillbak));
                if (sBill.equals(sBillbak)) {//说明内容一样，不管
                    delSameIds.add(bill_id);
                } else {//说明两个数据有差异，tmp1（新）的入库；tmp2（老）的从bak用删除，并且入求同存异表
                    daicha.add(sBillbak);
                    delIds.add(bill_id);
                    qtcy.add(sBill);
                }
            }

            if (!delIds.isEmpty()) {//需要删除
                //TODO
//            1.先把bak表中的老数据删掉
                sssfmIoBillMapper.delByIdsbak(delIds);
//            2.插求同存异表   待优化，可以改成批量
                for (SssfmIoBill it : qtcy) {
                    sssfmIoBillQtcyMapper.insertSelective(it);
                }
            }

            if (!delSameIds.isEmpty()) {//一模一样的数据也把bak表原来的干掉，重新插一遍
                sssfmIoBillMapper.delByIdsbak(delSameIds);
            }
        }

//      最后把新的数据入库
        sssfmIoBillMapper.insertAll("sssfm_io_bill_"+i);
    }


    public static void main(String[] args) {
        File dir = new File("E:\\data");//浏览F盘a文件夹下的所有内容
        //listFile(dir,"");
    }

    public void listFile(File dir, String spance) throws Exception {
        File[] files = dir.listFiles();   //列出所有的子文件
        for (File file : files) {
            if (file.isFile())//如果是文件，则输出文件名字
            {
                System.out.println(spance + file.getName());
                if ("bill.sql".equals(file.getName())) {
                    sssfmIoBillMapper.createTable("sssfm_io_bill" + "_" + spance);
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String sdata = br.readLine();
                    sdata = sdata.replaceAll("sssfm_io_bill", "sssfm_io_bill" + "_" + spance);
                    sssfmIoBillMapper.insertDate(sdata);

                }
                if ("item.sql".equals(file.getName())) {
                    sssfmIoBillItemMapper.createTable("sssfm_io_bill_item" + "_" + spance);
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String sdata = br.readLine();
                    sdata = sdata.replaceAll("sssfm_io_bill_item", "sssfm_io_bill_item" + "_" + spance);
                    sssfmIoBillItemMapper.insertDate(sdata);
                }
                if ("item01.sql".equals(file.getName())) {
                    sssfmIoBillItem01Mapper.createTable("sssfm_io_bill_item01" + "_" + spance);
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    String sdata = br.readLine();
                    sdata = sdata.replaceAll("sssfm_io_bill_item01", "sssfm_io_bill_item01" + "_" + spance);
                    sssfmIoBillItem01Mapper.insertDate(sdata);
                }
            } else if (file.isDirectory())//如果是文件夹，则输出文件夹的名字，并递归遍历该文件夹
            {
                System.out.println(spance + file.getName());
                //listFile(file,"|--"+spance);//递归遍历
                listFile(file, file.getName());//递归遍历
            }
        }
    }




    //子表
    private void insertItemTable(int i){
        String tableName = "sssfm_io_bill_item_";
        //计算目标需要   新增的数据
        List list = sssfmIoBillItemMapper.queryStep1(tableName+i);
        //判断 临时表 是否可以 接收目标表的数据  查询结果没有不需要 第三步
        List mb = sssfmIoBillItemMapper.queryStep2(tableName+i);
        if (mb != null && !mb.isEmpty()) {//需要处理
            List<SssfmIoBillItem> nowdata = sssfmIoBillItemMapper.selectByIds(tableName+i, mb);
            List<SssfmIoBillItem> bakdata = sssfmIoBillItemMapper.selectByIdsbak(mb);
            Map tmp1 = new HashMap<>();
            Map tmp2 = new HashMap<>();
            for (SssfmIoBillItem sb : nowdata) {
                tmp1.put(sb.getBillId()+"_"+sb.getSequNo(), sb);
            }
            for (SssfmIoBillItem sb : bakdata) {
                tmp2.put(sb.getBillId()+"_"+sb.getSequNo(), sb);
            }
            Iterator iterator = tmp1.entrySet().iterator();
//            List<SssfmIoBillItem> daicha = new ArrayList();//bak待插入
            List<String> delIds = new ArrayList<>();//bak待删除
            List<SssfmIoBillItem> qtcy = new ArrayList();//求同存异表
            List<String> delSameIds = new ArrayList<>();//bak和待插数据一模一样时记录下来，并删除

            while (iterator.hasNext()) {
                Map.Entry<String, SssfmIoBillItem> entry = (Map.Entry<String, SssfmIoBillItem>) iterator.next();
                String bill_id = (String) entry.getKey();
                SssfmIoBillItem sBill_1 = entry.getValue();
                SssfmIoBillItem sBill_bak = (SssfmIoBillItem) tmp2.get(bill_id);
                if(sBill_bak==null){//如果_1表的bill_id+sequ_no在bak表里边没有，则不处理，直接导进bak表
                    continue;
                }
                System.out.println(sBill_bak.equals(sBill_1));
                if (sBill_bak.equals(sBill_1)) {//说明内容一样，不管
                    delSameIds.add(bill_id);
                } else {//说明两个数据有差异，tmp1（新）的入库；tmp2（老）的从bak用删除，并且入求同存异表
//                    daicha.add(sBillbak);
                    delIds.add(bill_id);
                    qtcy.add(sBill_bak);
                }
            }

            if (!delIds.isEmpty()) {//需要删除
                //TODO
//            1.先把bak表中的老数据删掉
                for(String a:delIds){
                    SssfmIoBillItem abo = new SssfmIoBillItem();
                    abo.setBillId(a.split("_")[0]);
                    abo.setSequNo(Integer.valueOf(a.split("_")[1]));
                    sssfmIoBillItemMapper.delByIdsbak(abo);
                }

//            2.插求同存异表   待优化，可以改成批量
                for (SssfmIoBillItem it : qtcy) {
                    sssfmIoBillItemQtcyMapper.insertSelective(it);
                }
            }

            if (!delSameIds.isEmpty()) {//一模一样的数据也把bak表原来的干掉，重新插一遍
                for(String a:delSameIds){
                    SssfmIoBillItem abo = new SssfmIoBillItem();
                    abo.setBillId(a.split("_")[0]);
                    abo.setSequNo(Integer.valueOf(a.split("_")[1]));
                    sssfmIoBillItemMapper.delByIdsbak(abo);
                }
            }
        }

//      最后把新的数据入库
        sssfmIoBillItemMapper.insertAll(tableName+i);
    }










    //item01表
    private void insertItem01Table(int i){
        String tableName = "sssfm_io_bill_item01_";
        //计算目标需要   新增的数据
        List list = sssfmIoBillItem01Mapper.queryStep1(tableName+i);
        //判断 临时表 是否可以 接收目标表的数据  查询结果没有不需要 第三步
        List mb = sssfmIoBillItem01Mapper.queryStep2(tableName+i);
        if (mb != null && !mb.isEmpty()) {//需要处理
            List<SssfmIoBillItem01> nowdata = sssfmIoBillItem01Mapper.selectByIds(tableName+i, mb);
            List<SssfmIoBillItem01> bakdata = sssfmIoBillItem01Mapper.selectByIdsbak(mb);
            Map tmp_1 = new HashMap<>();
            Map tmp_bak = new HashMap<>();
            for (SssfmIoBillItem01 sb : nowdata) {
                tmp_1.put(sb.getBillId()+"_"+sb.getSequNo()+"_"+sb.getParentId(), sb);
            }
            for (SssfmIoBillItem01 sb : bakdata) {
                tmp_bak.put(sb.getBillId()+"_"+sb.getSequNo()+"_"+sb.getParentId(), sb);
            }
            Iterator iterator = tmp_1.entrySet().iterator();
//            List<SssfmIoBillItem> daicha = new ArrayList();//bak待插入
            List<String> delIds = new ArrayList<>();//bak待删除
            List<SssfmIoBillItem01> qtcy = new ArrayList();//求同存异表
            List<String> delSameIds = new ArrayList<>();//bak和待插数据一模一样时记录下来，并删除

            while (iterator.hasNext()) {
                Map.Entry<String, SssfmIoBillItem01> entry = (Map.Entry<String, SssfmIoBillItem01>) iterator.next();
                String bill_id = (String) entry.getKey();
                SssfmIoBillItem01 sBill_1 = entry.getValue();
                SssfmIoBillItem01 sBill_bak = (SssfmIoBillItem01) tmp_bak.get(bill_id);
                if(sBill_bak==null){//如果_1表的bill_id+sequ_no+parent_no在bak表里边没有，则不处理，直接导进bak表
                    continue;
                }
                System.out.println(sBill_bak.equals(sBill_1));
                if (sBill_bak.equals(sBill_1)) {//说明内容一样，不管
                    delSameIds.add(bill_id);
                } else {//说明两个数据有差异，tmp1（新）的入库；tmp2（老）的从bak用删除，并且入求同存异表
//                    daicha.add(sBill_1);
                    delIds.add(bill_id);
                    qtcy.add(sBill_bak);
                }
            }

            if (!delIds.isEmpty()) {//需要删除
                //TODO
//            1.先把bak表中的老数据删掉
                for(String a:delIds){
                    SssfmIoBillItem01 abo = new SssfmIoBillItem01();
                    abo.setBillId(a.split("_")[0]);
                    abo.setSequNo(Integer.valueOf(a.split("_")[1]));
                    abo.setParentId(Integer.valueOf(a.split("_")[2]));
                    sssfmIoBillItem01Mapper.delByIdsbak(abo);
                }

//            2.插求同存异表   待优化，可以改成批量
                for (SssfmIoBillItem01 it : qtcy) {
                    sssfmIoBillItem01QtcyMapper.insertSelective(it);
                }
            }

            if (!delSameIds.isEmpty()) {//一模一样的数据也把bak表原来的干掉，重新插一遍
                for(String a:delSameIds){
                    SssfmIoBillItem01 abo = new SssfmIoBillItem01();
                    abo.setBillId(a.split("_")[0]);
                    abo.setSequNo(Integer.valueOf(a.split("_")[1]));
                    abo.setParentId(Integer.valueOf(a.split("_")[2]));
                    sssfmIoBillItem01Mapper.delByIdsbak(abo);
                }
            }
        }

//      最后把新的数据入库
        sssfmIoBillItem01Mapper.insertAll(tableName+i);
    }

}
